//
//  Location.m
//  Weather-Test
//
//  Created by My Mac on 2017/4/30.
//  Copyright © 2017年 My Mac. All rights reserved.
//

#import "Location.h"
#import <UIKit/UIKit.h>

@implementation Location
//单例类：单例只有一个对象 共享位置管理器
+(instancetype)sharedLocationManager
{
    static Location *location = nil;
    if (!location) {
        location = [[Location alloc]init];
    }
    return location;
}

//重写init方法 超级方法（最先执行）
-(instancetype)init
{
    if (self = [super init]) {
        _manager = [[CLLocationManager alloc]init];
        // 请求用户授权,从IOS 8 开始，必须在程序中请求用户授权，除了写代码还要配置info.plist列表的键值对
        if ([_manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_manager requestWhenInUseAuthorization];
        }
        _manager.delegate = self;

        //开始定位
        [_manager startUpdatingLocation];
    }
    return self;
}

//引用方法
+(void)getUserLocation:(SaveLocation)saveLocationBlock
{
    Location *location = [Location sharedLocationManager];
    [location getLocation:saveLocationBlock];
}

-(void)getLocation:(SaveLocation)saveLocationBlock
{
    if (![CLLocationManager locationServicesEnabled]) {
        return;
    }
    //确定用户位置服务器
    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        //复制一个对象
        _saveLocation = [saveLocationBlock copy];
        //设置经纬度和默认位置
        _saveLocation(39.1111111,114.452122,@"株洲");
        return;
    }
    _saveLocation = [saveLocationBlock copy];
    //每隔100米定位一次
    self.manager.distanceFilter = 100;
    
}

#pragma mark - CLLocationManagerDelegate(代理方法)
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //创建CLLocation对象
    //纬度
    double lat = locations.lastObject.coordinate.latitude;
    //经度(经度本身是负值，反地理编码是正值)
    double lon = -locations.lastObject.coordinate.longitude;
    //初始化location对象，
    CLLocation *location = [[CLLocation alloc]initWithLatitude:lat longitude:lon];
    
    //地理编码
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    //反地理编码
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //防错处理
        if (placemarks.count == 0 || error) {
            NSLog(@"解析没有数据或者出错");
            return;
        }
        //遍历数组, 获取数据 --> 一般来讲就一个值
        for (CLPlacemark * placemark in placemarks) {
            _saveLocation(location.coordinate.latitude,location.coordinate.longitude,placemark.locality);
        }
    }];
    [_manager stopUpdatingLocation];
}
@end
